package com.anbinh.doctor.fragment.lichhen;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.anbinh.doctor.R;
import com.anbinh.doctor.model.DateTime;
import com.anbinh.doctor.model.ResponseAppointment;
import com.anbinh.doctor.model.ResponseAppointment.Item;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.IRcallBak;
import com.anbinh.doctor.utils.LichType;
import com.anbinh.doctor.utils.Utils;
import com.example.stickyheadergridview.GridItem;
import com.example.stickyheadergridview.StickyGridAdapter;
import com.krish.horizontalscrollview.CenterLockHorizontalScrollview;
import com.krish.horizontalscrollview.CustomListAdapter;
import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;
import com.tonicartos.widget.stickygridheaders.StickyGridHeadersGridView.OnHeaderClickListener;
import com.tonicartos.widget.stickygridheaders.StickyGridHeadersGridView.OnHeaderLongClickListener;

public class FragmentLichhen extends Fragment implements IRcallBak,
		OnItemClickListener, OnHeaderClickListener, OnHeaderLongClickListener {
	public static FragmentLichhen fragment = null;
	private View mView;
	private LinearLayout mLineTime;

	private CustomListAdapter customListAdapter;
	private CenterLockHorizontalScrollview centerLockHorizontalScrollview;

	private GridView mGridView;
	private List<GridItem> mGirdList = null;
	private static int section = 1;
	private Map<String, Integer> sectionMap = new HashMap<String, Integer>();
	private CircleProgressBar loadding;
	private GridItem currentItem;
	private StickyGridAdapter adapter;
	private UserLogin userLogin;
	private String mCurrentDay;

	public static FragmentLichhen newInstance() {
		if (fragment == null)
			fragment = new FragmentLichhen();

		return fragment;
	}

	public LinearLayout getmLineTime() {
		return mLineTime;
	}

	@Override
	public void onAttach(Activity activity) {
		Log.d("onAttach", "onAttach");
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_lichhen, null);
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		loadding = (CircleProgressBar) getView().findViewById(R.id.loadding);
		mGridView = (GridView) getView().findViewById(R.id.asset_grid);
		mGridView.setOnItemClickListener(this);

		onDisplayTime(-1, Integer.parseInt(Utils.getCurrentDay()) - 1);

	}

	public boolean isCheckAppoitmentExist() {
		if (mGridView.getVisibility() == View.VISIBLE)
			return true;
		return false;
	}

	public void onLoadData() {
		mGirdList = new ArrayList<GridItem>();
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);
		if (userLogin == null)
			return;
		loadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		ServerController.getInstance(getActivity()).requestGetAppointment(
				userLogin.getData().getToken(),
				getCurrentDay(),-1,
				new OnRequest<ResponseAppointment>() {

					@Override
					public void onSuccess(ResponseAppointment data) {
						Utils.disableEnableControls(true, mView);
						if (getActivity() == null)
							return;

						loadding.setVisibility(View.INVISIBLE);

						Utils.disableEnableControls(true, mView);
						if (data.getResponsecode() >= 0
								&& data.getData().getItems() != null
								&& data.getData().getItems().size() > 0) {
							mGridView.setVisibility(View.VISIBLE);
							for (int i = 0; i < data.getData().getItems()
									.size(); i++) {
								Item item = data.getData().getItems().get(i);
								for (int j = 0; j < item.getListSchedules()
										.size(); j++) {

									GridItem mGridItem = new GridItem(item
											.getAddress(), item.getNameDoctor());
									mGridItem.setGroupName("Box" + i);
									mGridItem.setAppointment(item);
									mGridItem.setPosition(j + 1);
									mGridItem.setSchedules(item
											.getListSchedules().get(j));

									mGirdList.add(mGridItem);

								}

							}

							for (ListIterator<GridItem> it = mGirdList
									.listIterator(); it.hasNext();) {
								GridItem mGridItem = it.next();
								String ym = mGridItem.getGroupName();
								if (!sectionMap.containsKey(ym)) {
									mGridItem.setSection(section);
									sectionMap.put(ym, section);
									section++;
								} else {
									mGridItem.setSection(sectionMap.get(ym));
								}
							}
							adapter = new StickyGridAdapter(getActivity(),
									mGirdList, mGridView);

							mGridView.setAdapter(adapter);
						} else {
							mGridView.setVisibility(View.GONE);
							Utils.showMessage(getActivity(),
									data.getDescription());
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						Utils.disableEnableControls(true, mView);
						loadding.setVisibility(View.INVISIBLE);
						Utils.showMessage(getActivity(),
								"Đã có lỗi xảy ra, Vui lòng quay lại sau giây lát");
						Utils.disableEnableControls(true, mView);
					}

				});
	}

	public void onDisplayTime(int month, final int currentDay) {
		int year = Integer.parseInt(Utils.getCurrentYear());
		int mMonth = month;
		if (month == -1) {
			mMonth = Integer.parseInt(Utils.getCurrentMonth());
		}
		Log.d("fullDate", mMonth + "");

		int lastDay = Integer.parseInt(Utils.getLastDay(mMonth, year));

		final ArrayList<DateTime> mListDate = new ArrayList<DateTime>();
		for (int i = 0; i < lastDay; i++) {
			String day = (i + 1) + "";
			DateTime item = new DateTime();
			item.setDate(day);
			item.setFullDate(Utils.getDateFormat(year + "-" + mMonth + "-"
					+ day));

			String dayName = Utils.getDayName(
					Integer.parseInt(Utils.getCurrentYear()), mMonth, (i + 1));
			item.setDateName(Utils.getMapDate().get(dayName));
			mListDate.add(item);
		}

		centerLockHorizontalScrollview = (CenterLockHorizontalScrollview) mView
				.findViewById(R.id.scrollView);
		customListAdapter = new CustomListAdapter(getActivity(),
				R.layout.item_date_time, mListDate, new IRcallBak() {

					@Override
					public void onDisplay(int type, Bundle data) {
						mCurrentDay = mListDate.get(type).getFullDate();
						centerLockHorizontalScrollview.setCenter(type);
						onLoadData();
					}
				});

		centerLockHorizontalScrollview.setAdapter(getActivity(),
				customListAdapter);
		new CountDownTimer(500, 100) {

			@Override
			public void onTick(long millisUntilFinished) {
			}

			@Override
			public void onFinish() {
				mCurrentDay = mListDate.get(currentDay).getFullDate();
				centerLockHorizontalScrollview.setCenter(currentDay);
				onLoadData();
			}
		}.start();

	}

	public String getCurrentDay() {
		return mCurrentDay;
	}

	@Override
	public void onDisplay(int type, Bundle data) {
	}

	@Override
	public boolean onHeaderLongClick(AdapterView<?> arg0, View arg1, long arg2) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onHeaderClick(AdapterView<?> arg0, View arg1, long arg2) {

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		currentItem = mGirdList.get(position);
		if (currentItem.getSchedules().getcheckDisable())// ngay be thua ngay
															// hien tai
		{
			Utils.showMessage(getActivity(),
					getResources().getString(R.string.lich_da_qua));
			return;
		}

		int status;
		String tmp = currentItem.getSchedules().getStatus();
		if (tmp.isEmpty()) {
			status = Utils.LICH_TRONG;// Lịch khám trống
		} else {
			status = Integer.parseInt(tmp);
		}

		if (status == LichType.LICHTAMDUNG_NUOCBIEN.getCode()) {
			Utils.showConfirmOnPause(currentItem.getSchedules()
					.getSchedules_pause_id(), getActivity(), new IRcallBak() {

				@Override
				public void onDisplay(int type, Bundle data) {
					switch (type) {
					case Utils.SHOW_PROCESS:
						loadding.setVisibility(View.VISIBLE);
						Utils.disableEnableControls(false, mView);

						break;

					case Utils.GONE_PROCESS:
						loadding.setVisibility(View.INVISIBLE);
						Utils.disableEnableControls(true, mView);

						break;
					case Utils.SUSSCESS:
						onLoadData();
						break;
					}
				}
			});
			return;
		}

		Bundle bundle = new Bundle();
		if (status == LichType.LICHTRONG_MAUXANH.getCode()) {
			bundle.putString(Utils.TITLE,
					getResources().getString(R.string.tao_lich_hen));
			bundle.putInt(Utils.KEY, Utils.CREATE_APPOINTMENT);

		} else {
			bundle.putInt(Utils.KEY, Utils.APPOINTMENT_DETAILT);
			bundle.putString(Utils.TITLE,
					getResources().getString(R.string.chi_tiet_lich_hen));
		}
		bundle.putInt(Utils.KEY_ID, currentItem.getSchedules().getId());
		bundle.putInt(Utils.KEY_STATUS, status);
		bundle.putInt(Utils.REQUEST_CODE, Utils.ONRESUME_LICHHEN);
		bundle.putBoolean(Utils.CUSTOMBAR, false);
		Utils.getNewIntent(getActivity(), bundle);
	}

	public GridItem getCurrentItem() {
		return currentItem;
	}

}
